package nil.ed.livechat.timeshift.sync.ext;

import com.google.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import nil.ed.livechat.timeshift.sync.common.RedisKeys;
import nil.ed.livechat.timeshift.sync.TsScheduledUpdateTask;
import redis.clients.jedis.JedisPubSub;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.DelayQueue;

/**
 * @author delin10
 * @since 2020/6/26
 **/
@Slf4j
public class PublishEventSubscriber extends JedisPubSub {

    @Inject
    private DelayQueue<TsScheduledUpdateTask.UpdateMetaData> queue;

    private Map<String, TsScheduledUpdateTask.UpdateMetaData> cache = new ConcurrentHashMap<>();

    @Inject
    private RedisSyncService redisSyncService;

    @Override
    public void onMessage(String channel, String message) {
        log.info("来自{}的消息{}", channel, message);
        if (channel.equals(RedisKeys.PUBLISH_TOPIC.getRawKey())) {
            TsScheduledUpdateTask.UpdateMetaData metaData = new TsScheduledUpdateTask.UpdateMetaData();
            if (cache.containsKey(message)) {
                metaData = cache.get(message);
            } else {
                cache.put(message, metaData);
            }
            metaData.setName(message);
            metaData.setInterval(2 * 1000);
            metaData.setIndex(-1);
            redisSyncService.clear(message);
            queue.put(metaData);
            log.info("加入流: {}", message);
        }
    }
}
